export class ExtensionError extends Error {
    constructor(message, code, originalError = null) {
        super(message);
        this.name = 'ExtensionError';
        this.code = code;
        this.originalError = originalError;
    }
}

export const ErrorCodes = {
    NETWORK_ERROR: 'NETWORK_ERROR',
    API_ERROR: 'API_ERROR',
    INVALID_STATE: 'INVALID_STATE',
    TRANSLATION_ERROR: 'TRANSLATION_ERROR',
    UNKNOWN_ERROR: 'UNKNOWN_ERROR',
    AI_ERROR: 'AI_ERROR'
};

export const ErrorMessages = {
    [ErrorCodes.NETWORK_ERROR]: '网络连接失败，请检查网络后重试',
    [ErrorCodes.API_ERROR]: '服务接口异常，请稍后重试',
    [ErrorCodes.INVALID_STATE]: '扩展状态异常，请刷新页面后重试',
    [ErrorCodes.TRANSLATION_ERROR]: '翻译服务异常，请稍后重试',
    [ErrorCodes.UNKNOWN_ERROR]: '发生未知错误，请刷新页面后重试',
    [ErrorCodes.AI_ERROR]: 'AI 服务异常，请稍后重试'
};

export function handleError(error, logger) {
    if (error instanceof ExtensionError) {
        return error;
    }

    if (error.message?.includes('Extension context invalidated')) {
        return new ExtensionError(
            ErrorMessages[ErrorCodes.INVALID_STATE],
            ErrorCodes.INVALID_STATE,
            error
        );
    }

    if (error instanceof TypeError || error.name === 'NetworkError') {
        return new ExtensionError(
            ErrorMessages[ErrorCodes.NETWORK_ERROR],
            ErrorCodes.NETWORK_ERROR,
            error
        );
    }

    logger.error(error, 'Unexpected error occurred');
    return new ExtensionError(
        ErrorMessages[ErrorCodes.UNKNOWN_ERROR],
        ErrorCodes.UNKNOWN_ERROR,
        error
    );
} 